package cn.darkfire.web.Controller;

import cn.darkfire.web.POJO.LoginUser;
import cn.darkfire.web.Service.UserService;
import cn.darkfire.web.Service.impl.UserServiceImpl;
import cn.darkfire.web.Utils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "edit.do")
public class EditController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if(req.getParameter("username").length()>3
                &&req.getParameter("oldPass").length()>=5
                &&req.getParameter("newPass").length()>=5){
            UserService userService = new UserServiceImpl();
            try{
                LoginUser oldUser  = userService.searchUserByNameTrue(req.getParameter("username"));
                System.out.println(oldUser.getPassword()+","+DataUtils.getInstance().stringToMD5(req.getParameter("oldPass")));
                if(oldUser.getPassword().equalsIgnoreCase(DataUtils.getInstance().stringToMD5(req.getParameter("oldPass")))){
                    if(userService.changePassword(new LoginUser(req.getParameter("username"),req.getParameter("newPass"))).getCode()==200){
                        req.getSession().setAttribute("success", "修改用户成功！");
                        req.getSession().removeAttribute("user"); //删除用户登录
                        resp.sendRedirect("./login.jsp");
                    }else{
                        req.getSession().setAttribute("error", "修改用户失败！");
                        resp.sendRedirect("./edit.jsp");
                    }
                }else{
                    req.getSession().setAttribute("error", "修改用户失败！原密码不正确！");
                    resp.sendRedirect("./edit.jsp");
                }
            }catch (Exception e){
                e.printStackTrace();
                req.getSession().setAttribute("error", "修改用户失败！！用户不存在！");
                resp.sendRedirect("./edit.jsp");
            }
        }else{
            req.getSession().setAttribute("error", "修改用户失败！密码格式不正确！");
            resp.sendRedirect("./edit.jsp");
        }
    }
}
